import axios from 'axios'
import { Message, Loading } from 'element-ui'
import { mdApiBase } from './config.service'
import localStorageService from './localStorage.service'
import { _dataEncryption } from './encryption.service'
import httpCodeService from './httpCode.service'

const httpConfig = {
  loading: null,
  msgFlag: false
}

/** 
 * 超时
 */
axios.defaults.timeout = 1000000
axios.defaults.baseURL = `${mdApiBase}`
axios.defaults.retry = 10
axios.defaults.retryDelay = 1000

/** 
 * 请求拦截
 */
axios.interceptors.request.use(config => {
  if (config.showLoading !== undefined && !config.showLoading) {
    httpConfig.msgFlag = false

    if (httpConfig.loading) httpConfig.loading.close()
  }
  else {
    httpConfig.msgFlag = false

    httpConfig.loading = Loading.service({ text: '加载中...' })
  }

  const model = config.data || {}

  const signModel = _dataEncryption(model)

  if (['post', 'put', 'patch'].includes(config.method)) {
    config.data = signModel
  }

  if (['get', 'delete', 'head'].includes(config.method)) {
    const queryParams = Object.keys(signModel).map(m => { return `${m}=${signModel[m]}` }).join('&')

    config.url = `${config.url}?${queryParams}`
  }

  if (localStorageService.getItem('Authorization')) {
    config.headers.Authorization = `Bearer ${localStorageService.getItem('Authorization')}`
  }

  return config
}, error => {
  console.log(error);
  return Promise.reject(error)
})
/** 
 * 响应拦截
 */
axios.interceptors.response.use(response => {
  if (response.status !== 200) {
    Message.error('服务器异常')
    return Promise.reject(response)
  }

  let { data } = response

  if (response.status == 200) {
    // 成功
    if (data.code === '200') {
      if (httpConfig.loading) httpConfig.loading.close()

      return data
    }

    // 登录超时
    if (data.code === '401') {
      if (httpConfig.loading) httpConfig.loading.close()

      localStorage.clear()

      Message.error('登录超时')

      setTimeout(() => {
        window.location.href = '/login'
      }, 1000)

      return Promise.reject(response)
    }

    // 异常
    if (httpConfig.loading) httpConfig.loading.close()

    if (!httpConfig.msgFlag) {
      Message.error(data.msg || '服务器异常')
      httpConfig.msgFlag = true
    }

    return Promise.reject(response)
  } else {
    if (httpConfig.loading) httpConfig.loading.close()

    if (!httpConfig.msgFlag) {
      Message.error(data.msg || '服务器异常')
      httpConfig.msgFlag = true
    }

    return Promise.reject(response)
  }
}, error => { ResponseStatus(error); return Promise.reject(error) })
/** 
 * 响应状态拦截
 */
let ResponseStatus = (error) => {
  if (httpConfig.loading) httpConfig.loading.close()

  const response = error.response

  if (response.status === 401) {
    localStorage.clear()

    if (!httpConfig.msgFlag) {
      Message.error('登陆超时')
      httpConfig.msgFlag = true
    }

    setTimeout(() => {
      window.location.href = '/login'
    }, 1000)
  }
  else {
    const response = error.response

    const msg = httpCodeService[response.status]

    if (!httpConfig.msgFlag) {
      Message.error(msg || response.statusText)
      httpConfig.msgFlag = true
    }
  }
}

const HttpService = axios

export default HttpService
